package cn.wolfcode.web.controller;


import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.UnreadNotice;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.INoticeService;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LoginController {
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IPermissionService permissionService;
    @Autowired
    private INoticeService noticeService;

    @RequestMapping("/empLogin")
    @ResponseBody
    public JsonResult login(Employee employee) {
//        try {
        //查询是否账号禁用
        employeeService.queryStatusByUsername(employee.getUsername());

        //查询账号密码
        Employee e = employeeService.queryByUsernameAndPassword(employee);

        UserContext.setCurrentUser(e);
        //session.setAttribute("USER_IN_SESSION", e);
        if (!e.isAdmin()) {
            List<String> permissions = permissionService.queryPermissionByEmpId(e.getId());
            //session.setAttribute("EXPRESSION_IN_SESSION", permissions);
            UserContext.setExpressions(permissions);
        }


        Long empId = UserContext.getCurrentUser().getId();

        UnreadNotice unreadNotice = new UnreadNotice();
        //查询出所有未读的公告,设置进去对象里面
        unreadNotice.setNotices(noticeService.queryUnreadNotices(empId));
        //查询当前用户未读公告的条数,设置进去对象里面
        unreadNotice.setSize(noticeService.queryUnreadSize(empId));
        //设置未读的公告 , 把封装好的数据放到session中去
        UserContext.setUnreadNotice(unreadNotice);
        return new JsonResult();
//        } catch (Exception ex) {
//            ex.printStackTrace();
//            return new JsonResult(false, ex.getMessage());
//        }
    }

    @RequestMapping("/empLogout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/login.html";
    }

    @RequestMapping("/nopermission")
    public String nopermission() {
        return "common/nopermission";
    }
}
